﻿using Smokey.Client.Contexts;
using System.Configuration;
namespace Smokey.Client.Screens.Common {
    internal class ConnectionStringSetupViewModel : ViewModelBase {

        public ConnectionStringSetupViewModel(ViewModelContext context)
            : base(context) {
        }

        private string server = "(local)";
        public string Server {
            get {
                return server;
            }

            set {
                if (server != value) {
                    server = value;
                    OnPropertyChanged("Server");
                }
            }
        }

        private string databaseName = "Smokey";
        public string DatabaseName {
            get {
                return databaseName;
            }
            set {
                if (databaseName != value) {
                    databaseName = value;
                    OnPropertyChanged("DatabaseName");
                }
            }
        }

        private string errorMessage;
        public string ErrorMessage {
            get {
                return errorMessage;
            }
            set {
                if (errorMessage != value) {
                    errorMessage = value;
                    OnPropertyChanged("ErrorMessage");
                }
            }
        }

        private string GetConnectionString() {
            return string.Format("Server={0};Database={1};Integrated Security=true",
                server,
                databaseName);
        }

        public void TrySaveConnectionString() {
            if (App.Current.TestDatabaseConnection(GetConnectionString())) {
                ConfigurationManager.AppSettings["ConnectionString"] = GetConnectionString();
                Context.ShowApplicationSearchScreen();
            } else {
                ErrorMessage = "Connection failed. Please check your details.";
            }
        }
    }
}
